package com.scheduler.utils.okhttp;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Objects;


public class OkHttpClient {

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private OkHttpClient() {
    }

    private static okhttp3.OkHttpClient instance() {
        return HttpClientHolder.INSTANCE;
    }

    public static String doGet(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        return execute(request);
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPost(String url, Object param) {
        return doPost(url, JSONObject.toJSONString(param));
    }

    public static String doPost(String url, String json) {
        return doPost(url, json, (Header[]) null);
    }

    public static String doPost(String url, String json, Header... headers) {
        Request.Builder requestBuilder = new Request.Builder()
                .url(url);

        if (StringUtils.isNotBlank(json)) {
            RequestBody requestBody = RequestBody.create(JSON, json);
            requestBuilder.post(requestBody);
        } else {
            // 空数据
            RequestBody requestBody = RequestBody.create(null, "");
            requestBuilder.post(requestBody);
        }
        if (headers != null) {
            for (Header header : headers) {
                if (header == null || header.name == null || header.value == null) {
                    continue;
                }
                requestBuilder.addHeader(header.name, header.value);
            }
        }
        Request request = requestBuilder.build();
        return execute(request);
    }

    private static String execute(Request request) {
        try (Response response = instance().newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new SchedulerCenterException("HTTP接口调用异常，异常状态码为[" + response.code() + "]，异常信息为[" + response.message() + "]");
            }

            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new SchedulerCenterException("HTTP接口调用异常，响应体为空");
            }


            return responseBody.string();
        } catch (IOException e) {
            throw new SchedulerCenterException("HTTP接口调用异常：", e);
        }
    }

    private static class HttpClientHolder {
        private static final okhttp3.OkHttpClient INSTANCE = new okhttp3.OkHttpClient.Builder().build();
    }

    public static class Header {
        private String name;
        private String value;

        public static Header of(String name, String value) {
            Header header = new Header();
            header.name = name;
            header.value = value;
            return header;
        }
    }
}

